package com.liujun.io.netty.eight.book.server;

import com.liujun.io.netty.eight.protobuf.SubscribeReqProto;
import com.liujun.io.netty.eight.protobuf.SubscribeReqProto.SubscribeReq;
import com.liujun.io.netty.eight.protobuf.SubscribeRespProto;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class SubReqServerHandler extends ChannelHandlerAdapter {


	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
		if("liujun".equalsIgnoreCase(req.getUserName()))
		{
			System.out.println("Service accept client subscribe req : [" + req+ "]" );
			ctx.writeAndFlush(resp(req.getSubReqID()));
		}
	}
	
	private SubscribeRespProto.SubscrinbeResp resp(int subReqID)
	{
		SubscribeRespProto.SubscrinbeResp.Builder builder = SubscribeRespProto.SubscrinbeResp.newBuilder();
		builder.setSubReqID(subReqID);
		builder.setRespCode(0);
		builder.setDesc("Netty book order success ,3 days later,sent to the designated address");
		return builder.build();
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	
}
